package com.kcsoft.welcome.controller;

import com.alibaba.excel.EasyExcel;
import com.kcsoft.welcome.listener.ExcelListener;
import com.kcsoft.welcome.pojo.PageBean;
import com.kcsoft.welcome.pojo.Pfence;
import com.kcsoft.welcome.pojo.Result;
import com.kcsoft.welcome.service.PfenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.http.WebSocket;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/pfence")
public class PfenceController {

    @Autowired
    PfenceService pfenceService;

    @PostMapping("/add")
    public Result add(@RequestParam("file")MultipartFile file){
        if (file.isEmpty()){
            return Result.error("文件为空");
        }
        String filename = file.getOriginalFilename();
        if (!filename.endsWith(".xlsx") || filename.endsWith(".xls")){
            return Result.error("文件格式错误");
        }

        try {
            ExcelListener el = new ExcelListener();

            EasyExcel.read(file.getInputStream(), Pfence.class, el)
                    .sheet()
                    .doRead();

            List<Pfence> pfList = el.getDataList();

            pfList.forEach(
                    pf -> pfenceService.add(pf)
            );

        } catch (IOException e) {
            return Result.error("文件读取失败");
        }

        return Result.success();
    }

    @GetMapping("/list")
    public Result<List<Pfence>> list(LocalDate date){
        return Result.success(pfenceService.list(date));
    }

    @PostMapping("/update")
    public Result update(@RequestParam Integer id,@RequestParam Integer pf) {
        pfenceService.update(id, pf);
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(Integer id) {
        pfenceService.delete(id);
        return Result.success();
    }

    @GetMapping("/dates")
    public Result<List<LocalDate>> dates() {
        return Result.success(pfenceService.dates());
    }
}
